<?php

namespace app\site\controller;

use app\common\model\ShopFlashsaleGoodsModel;
use app\common\model\ShopFlashsaleModel;
use app\common\model\ShopGoodsSkuModel;
use think\Request;

class ShopFlashsaleController extends BaseController
{
    private $flashsaleModel;
    private $flashsaleGoodsModel;

    /**
     * 初始化
     */
    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->flashsaleModel      = new ShopFlashsaleModel();
        $this->flashsaleGoodsModel = new ShopFlashsaleGoodsModel();
    }

    /**
     * 活动列表
     */
    public function index()
    {
        $query          = $this->request->request();
        $map['site_id'] = $this->getSiteId();
        $status         = $this->request->param('status', -1);
        $flashsaleName  = $this->request->param('flashsale_name');
        if ($status >= 0) {
            $map['status'] = $status;
        }
        if (!empty($flashsaleName)) {
            $map['flashsale_name'] = ['like', '%' . $flashsaleName . '%'];
        }
        $list = $this->flashsaleModel->where($map)->paginate(12, false, ['query' => $query]);
        $this->assign('query', $query);
        $this->assign('list', $list);
        return $this->fetch();
    }

    /**
     * 添加活动
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            $data            = $this->request->param();
            $data['site_id'] = $this->getSiteId();
            $result          = $this->validate($data, [
                'flashsale_name|活动名称' => 'require',
                'begin_time|开始日期'     => 'date',
                'end_time|结束日期'       => 'date',
            ]);
            if (true !== $result) {
                $this->error($result);
            }
            $data['site_name']  = $this->getSiteInfo('site_name');
            $data['begin_time'] = strtotime($data['begin_time']);
            $data['end_time']   = strtotime($data['end_time']);
            $data['status']     = 1;  //默认审核
            if ($this->flashsaleModel->addData($data)) {
                $this->success('添加成功！', url('index'));
            } else {
                $this->error($this->flashsaleModel->getError());
            }
        }
        return $this->fetch();
    }

    /**
     * 编辑活动
     */
    public function edit()
    {
        if ($this->request->isAjax()) {
            $data   = $this->request->param();
            $result = $this->validate($data, [
                'flashsale_name|活动名称' => 'require',
                'begin_time|开始日期'     => 'date',
                'end_time|结束日期'       => 'date',
            ]);
            if (true !== $result) {
                $this->error($result);
            }
            $data['begin_time'] = strtotime($data['begin_time']);
            $data['end_time']   = strtotime($data['end_time']);
            if ($this->flashsaleModel->editData($data)) {
                //同步附表
                $this->flashsaleGoodsModel->where('flashsale_id', $data['flashsale_id'])->update([
                    'flashsale_name'    => $data['flashsale_name'],
                    'flashsale_explain' => $data['flashsale_explain'],
                ]);
                $this->success('操作成功！', url('index'));
            } else {
                $this->error($this->flashsaleModel->getError());
            }
        }
        $flashsaleId = $this->request->param('flashsale_id/d');
        $info        = $this->flashsaleModel->get($flashsaleId);
        $this->assign('info', $info);
        return $this->fetch();
    }

    /**
     * 删除活动
     */
    public function del()
    {
        $flashsaleId = $this->request->param('flashsale_id/d');
        $skuids      = $this->flashsaleGoodsModel->where('flashsale_id', $flashsaleId)->column('sku_id');
        if ($skuids) {
            $goodsSkuModel = new ShopGoodsSkuModel();
            $goodsSkuModel->where('sku_id', 'in', $skuids)->setField(['promotion_type' => 0, 'promotion_price' => 0]); //恢复对应商品活动状态
            $this->flashsaleGoodsModel->where('flashsale_id', $flashsaleId)->delete();
        }
        $this->flashsaleModel->where('flashsale_id', $flashsaleId)->delete();
        $this->success('操作成功！');
    }

    /**
     * 活动商品
     */
    public function goods()
    {
        $flashsaleId         = $this->request->param('flashsale_id/d');
        $map['flashsale_id'] = $flashsaleId;
        $info                = $this->flashsaleModel->where($map)->find();
        $info                = $info->append(['status_text'])->toArray();
        $item                = $this->flashsaleGoodsModel->where($map)->select();
        $info['item']        = $item;
        $this->assign('info', $info);
        return $this->fetch();
    }

    /**
     * 添加活动商品
     */
    public function addGoods()
    {
        $flashsaleId = $this->request->param('flashsale_id/d');
        $skuList     = $this->request->param('sku_list/a');
        if (empty($skuList)) {
            $this->error('请选择活动商品！');
        }
        $valid = true;
        foreach ($skuList as $k => $v) {
            if (empty($v['flashsale_price'])) {
                $valid = false;
                break; //终止循环
            }
            if ($v['flashsale_price'] > $v['simple_price']) {
                $valid = false;
                break;
            }
        }
        if ($valid == false) {
            $this->error('请正确填写，折扣价格必须小于销售价格！');
        }
        $map['flashsale_id'] = $flashsaleId;
        $info                = $this->flashsaleModel->where($map)->find();
        $promotion           = [];
        $dataList            = [];
        foreach ($skuList as $skuid => $value) {
            $dataList[]  = [
                'flashsale_id'      => $info['flashsale_id'],
                'flashsale_name'    => $info['flashsale_name'],
                'flashsale_explain' => $info['flashsale_explain'],
                'goods_id'          => $value['goods_id'],
                'sku_id'            => $value['sku_id'],
                'site_id'           => $value['site_id'],
                'site_name'         => $value['site_name'],
                'goods_name'        => $value['goods_name'],
                'sku_name'          => $value['sku_name'],
                'market_price'      => $value['market_price'],
                'simple_price'      => $value['simple_price'],
                'flashsale_price'   => $value['flashsale_price'],
                'goods_thumb'       => $value['goods_thumb'],
                'begin_time'        => $info['begin_time'],
                'end_time'          => $info['end_time'],
                'status'            => 1,
            ];
            $skuList[]=['sku_id'=>$value['sku_id'],'promotion_type'=>1,'promotion_price'=>$value['flashsale_price']];
            $promotion[] = $value['sku_id'];
        }
        if ($dataList) {
            $goodsSkuModel = new ShopGoodsSkuModel();
            $this->flashsaleGoodsModel->saveAll($dataList);
            $goodsSkuModel->saveAll($skuList); //标记对应商品活动状态
        }
        $this->success('操作成功！');
    }

    /**
     * 删除活动商品
     */
    public function delGoods()
    {
        $flashsaleGoodsId = $this->request->param('flashsale_goods_id/d');
        $skuid            = $this->request->param('sku_id/d');
        $goodsSkuModel    = new ShopGoodsSkuModel();
        $goodsSkuModel->where('sku_id', $skuid)->setField(['promotion_type'=>0,'promotion_price'=>0]);  //标记对应商品活动状态
        $this->flashsaleGoodsModel->where('flashsale_goods_id', $flashsaleGoodsId)->delete();
        $this->success('操作成功！');
    }

}
